<template>
  <div class="map-address-selector">
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>地址选择</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        
        <div class="search-section">
          <div class="search-input-group">
            <input 
              v-model="searchKeyword" 
              @keyup.enter="searchAddress"
              placeholder="请输入地址进行搜索" 
              class="search-input"
            />
            <button @click="searchAddress" class="search-btn">搜索</button>
            <button @click="clearSearch" class="clear-btn">×</button>
          </div>
        </div>

        <div class="common-addresses">
          <h4>常用地址</h4>
          <div class="address-buttons">
            <button 
              v-for="address in commonAddresses" 
              :key="address"
              @click="selectCommonAddress(address)"
              class="address-btn"
            >
              {{ address }}
            </button>
          </div>
        </div>

        <div id="map-container" class="map-container">
          <div v-if="!mapLoaded" class="map-loading">
            <div class="loading-spinner"></div>
            <p>地图加载中...</p>
          </div>
        </div>

        <div v-if="searchResults.length > 0" class="search-results">
          <h4>搜索结果</h4>
          <div class="result-list">
            <div 
              v-for="result in searchResults" 
              :key="result.uid"
              @click="selectAddress(result)"
              class="result-item"
            >
              <div class="result-title">{{ result.title }}</div>
              <div class="result-address">{{ result.address }}</div>
            </div>
          </div>
        </div>

        <div class="modal-actions">
          <button @click="confirmSelection" class="confirm-btn">确认选择</button>
          <button @click="closeModal" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'

interface Props {
  modelValue?: string
  showModal: boolean
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'update:showModal', value: boolean): void
  (e: 'confirm', address: string, location: { lng: number, lat: number }): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  showModal: false
})

const emit = defineEmits<Emits>()

const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const selectedAddress = ref('')
const selectedLocation = ref({ lng: 0, lat: 0 })
const mapLoaded = ref(false)
let map: any = null
let localSearch: any = null

const commonAddresses = ref([
  '北京市朝阳区',
  '上海市浦东新区', 
  '广州市天河区',
  '深圳市南山区',
  '杭州市西湖区',
  '成都市锦江区',
  '武汉市江汉区',
  '西安市雁塔区'
])

const AK = 'JejBYDSsA76GlOH5xNMJmAjXghFPbdYA'

const initMap = async () => {
  try {
    console.log('开始初始化地图...')
    mapLoaded.value = false
    
    const mapContainer = document.getElementById('map-container')
    if (!mapContainer) {
      console.error('地图容器不存在')
      return
    }
    
    // 检查容器尺寸
    const rect = mapContainer.getBoundingClientRect()
    console.log('地图容器尺寸:', rect.width, 'x', rect.height)
    
    if (rect.width === 0 || rect.height === 0) {
      console.error('地图容器尺寸为零，等待容器渲染...')
      // 如果容器尺寸为零，等待一段时间后重试
      setTimeout(() => {
        initMap()
      }, 500)
      return
    }
    
    // 检查容器可见性
    const style = window.getComputedStyle(mapContainer)
    console.log('地图容器样式:', {
      display: style.display,
      visibility: style.visibility,
      opacity: style.opacity
    })
    
    // 强制设置容器尺寸和样式
    mapContainer.style.width = '100%'
    mapContainer.style.height = '300px'
    mapContainer.style.display = 'block'
    mapContainer.style.visibility = 'visible'
    mapContainer.style.opacity = '1'
    
    if (typeof (window as any).BMap === 'undefined') {
      console.log('百度地图API未加载，开始加载...')
      await loadBaiduMapAPI()
    }
    
    await nextTick()
    
    const BMap = (window as any).BMap
    if (!BMap) {
      console.error('百度地图API加载失败')
      return
    }
    
    console.log('创建地图实例...')
    
    // 确保容器为空
    mapContainer.innerHTML = ''
    
    map = new BMap.Map('map-container')
    
    const point = new BMap.Point(116.404, 39.915)
    map.centerAndZoom(point, 12)
    
    console.log('地图创建成功，添加控件...')
    
    map.addControl(new BMap.NavigationControl())
    map.addControl(new BMap.ScaleControl())
    map.addControl(new BMap.OverviewMapControl())
    map.addControl(new BMap.MapTypeControl())
    
    localSearch = new BMap.LocalSearch(map, {
      onSearchComplete: (results: any) => {
        if (localSearch.getStatus() === 0) {
          const pois = results.getPoi(0)
          if (pois) {
            const point = pois.point
            map.centerAndZoom(point, 15)
            
            const marker = new BMap.Marker(point)
            map.addOverlay(marker)
            
            const infoWindow = new BMap.InfoWindow(pois.title + '<br/>' + pois.address)
            marker.addEventListener('click', () => {
              map.openInfoWindow(infoWindow, point)
            })
          }
        }
      }
    })
    
    map.addEventListener('click', (e: any) => {
      const point = e.point
      map.clearOverlays()
      
      const marker = new BMap.Marker(point)
      map.addOverlay(marker)
      
      const geoc = new BMap.Geocoder()
      geoc.getLocation(point, (result: any) => {
        if (result) {
          selectedAddress.value = result.address
          selectedLocation.value = { lng: point.lng, lat: point.lat }
        }
      })
    })
    
    console.log('地图初始化完成')
    mapLoaded.value = true
  } catch (error) {
    console.error('地图初始化失败:', error)
    mapLoaded.value = false
  }
}

const loadBaiduMapAPI = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof (window as any).BMap !== 'undefined') {
      console.log('百度地图API已存在')
      resolve()
      return
    }
    
    console.log('开始加载百度地图API...')
    
    // 检查是否已有加载中的脚本
    const existingScript = document.querySelector('script[src*="api.map.baidu.com"]')
    if (existingScript) {
      console.log('百度地图API脚本已存在，等待加载...')
      const checkInterval = setInterval(() => {
        if (typeof (window as any).BMap !== 'undefined') {
          clearInterval(checkInterval)
          console.log('百度地图API加载完成')
          resolve()
        }
      }, 100)
      
      setTimeout(() => {
        clearInterval(checkInterval)
        console.error('百度地图API加载超时')
        reject(new Error('百度地图API加载超时'))
      }, 15000) // 增加超时时间到15秒
      return
    }
    
    const callbackName = 'initBaiduMap_' + Date.now()
    ;(window as any)[callbackName] = () => {
      console.log('百度地图API加载成功')
      resolve()
      delete (window as any)[callbackName]
    }
    
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${AK}&callback=${callbackName}`
    script.onerror = (error) => {
      console.error('百度地图API加载失败:', error)
      reject(error)
    }
    
    script.onload = () => {
      console.log('百度地图API脚本加载完成')
    }
    
    document.head.appendChild(script)
    console.log('百度地图API脚本已添加到页面')
  })
}

const searchAddress = () => {
  if (!searchKeyword.value.trim()) return
  
  if (localSearch) {
    localSearch.search(searchKeyword.value)
  }
  
  const script = document.createElement('script')
  script.src = `https://api.map.baidu.com/place/v2/search?query=${encodeURIComponent(searchKeyword.value)}&region=全国&output=json&ak=${AK}&callback=handleSearchResult`
  
  ;(window as any).handleSearchResult = (data: any) => {
    if (data && data.results) {
      searchResults.value = data.results.slice(0, 10)
    }
    document.head.removeChild(script)
  }
  
  document.head.appendChild(script)
}

const selectCommonAddress = (address: string) => {
  searchKeyword.value = address
  searchAddress()
}

const selectAddress = (result: any) => {
  selectedAddress.value = result.title + ' - ' + result.address
  selectedLocation.value = { lng: result.location.lng, lat: result.location.lat }
  
  const BMap = (window as any).BMap
  
  const point = new BMap.Point(result.location.lng, result.location.lat)
  map.centerAndZoom(point, 15)
  
  map.clearOverlays()
  
  const marker = new BMap.Marker(point)
  map.addOverlay(marker)
  
  const infoWindow = new BMap.InfoWindow(result.title + '<br/>' + result.address)
  marker.addEventListener('click', () => {
    map.openInfoWindow(infoWindow, point)
  })
}

const clearSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
}

const confirmSelection = () => {
  if (selectedAddress.value) {
    emit('update:modelValue', selectedAddress.value)
    emit('confirm', selectedAddress.value, selectedLocation.value)
    closeModal()
  }
}

const closeModal = () => {
  emit('update:showModal', false)
  clearSearch()
  selectedAddress.value = ''
  selectedLocation.value = { lng: 0, lat: 0 }
  mapLoaded.value = false
  
  // 清理地图实例
  if (map) {
    try {
      map.clearOverlays()
      map = null
    } catch (error) {
      console.error('清理地图实例失败:', error)
    }
  }
}

watch(() => props.showModal, async (newVal) => {
  if (newVal) {
    console.log('弹窗显示，开始初始化地图...')
    await nextTick()
    // 等待DOM完全渲染后再初始化地图
    setTimeout(() => {
      initMap()
    }, 1000)
  } else {
    // 弹窗关闭时清理地图
    if (map) {
      try {
        map.clearOverlays()
        map = null
      } catch (error) {
        console.error('清理地图实例失败:', error)
      }
    }
    mapLoaded.value = false
  }
}, { immediate: true })

onMounted(() => {
  if (props.showModal) {
    console.log('组件挂载时弹窗已显示，初始化地图...')
    setTimeout(() => {
      initMap()
    }, 200)
  }
})
</script>

<style scoped>
.map-address-selector {
  position: relative;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.search-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-btn:hover {
  background: #40a9ff;
}

.clear-btn {
  background: #f5f5f5;
  border: 1px solid #ddd;
  color: #666;
  padding: 10px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.clear-btn:hover {
  background: #e6e6e6;
}

.common-addresses {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.common-addresses h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.address-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}

.address-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  text-align: center;
}

.address-btn:hover {
  background: #40a9ff;
}

.map-container {
  height: 300px;
  width: 100%;
  margin: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  position: relative;
  background: #f9f9f9;
  /* 确保容器可见 */
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  min-height: 300px;
  min-width: 100%;
}

.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f9f9f9;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e3e3e3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.map-loading p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-results {
  padding: 0 20px 20px;
  border-bottom: 1px solid #eee;
}

.search-results h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.result-list {
  max-height: 200px;
  overflow-y: auto;
}

.result-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:hover {
  background: #f5f5f5;
}

.result-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  padding: 20px;
}

.confirm-btn,
.cancel-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.confirm-btn {
  background: #52c41a;
  color: white;
}

.confirm-btn:hover {
  background: #73d13d;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e6e6e6;
}
</style>
